package com.xiang.action;

import com.xiang.doman.Account;
import com.xiang.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AccountActionImpl implements AccountAction{
    @Autowired
    AccountMapper accountMapper;
    @Override
    public boolean prepare(BusinessActionContext actionContext, double amount, int accountId) {
        Account account=accountMapper.selectById(accountId);
        if(account.getMoney()<amount){
            throw new RuntimeException("余额不足！");
        }
        /**
         * todo  【幂等性、空回滚 、悬挂问题（框架已解决：@TwoPhaseBusinessAction注解配置）】
         * 相关: https://seata.apache.org/zh-cn/blog/seata-tcc-fence/#4-tcc-%E5%AD%98%E5%9C%A8%E9%97%AE%E9%A2%98
         */

        log.info("Account 执行  try 了。。。");
        accountMapper.reduceMoney(amount,accountId);


        return true;
    }

    @Override
    public boolean commit(BusinessActionContext actionContext) {
        log.info("Account 执行  commit 了。。。");
        double amount =  actionContext.getActionContext("amount",Double.class);
        int accountId =  actionContext.getActionContext("accountId",Integer.class);

        accountMapper.commitReduce(amount,accountId);

        return true;
    }

    @Override
    public boolean rollback(BusinessActionContext actionContext) {
        log.info("Account 执行  cancle 了。。。");
        double amount =  actionContext.getActionContext("amount",Double.class);
        int accountId =  actionContext.getActionContext("accountId",Integer.class);

        accountMapper.cancleReduce(amount,accountId);
        return true;
    }
}
